#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
最终修复版：正确匹配 onClick(View v) { 和 switch (v.getId()) {
支持转换 switch 为 if-else 链
"""

import re
import sys
from pathlib import Path

def get_onclick_param(line: str):
    """从 'public void onClick(View v) {' 提取参数名 v"""
    m = re.search(r'public\s+void\s+onClick\s*\(\s*View\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\)\s*\{', line)
    return m.group(1) if m else None

def get_switch_var(line: str):
    """从 'switch (v.getId()) {' 提取变量名 v"""
    m = re.search(r'switch\s*\(\s*([a-zA-Z_$][a-zA-Z0-9_$]*)\.getId\(\)\s*\)\s*\{', line)
    return m.group(1) if m else None

CASE_PATTERN = re.compile(r'^(\s*)case\s+(R\.id\.[a-zA-Z_]\w*)\s*:\s*(.*)$')
BREAK_PATTERN = re.compile(r'^\s*break\s*;?\s*(//.*)?$')

def is_switch_end(line: str) -> bool:
    stripped = line.strip()
    return stripped == '}' or stripped.startswith('}')

def process_switch_block(lines, start_idx, var_name, base_indent):
    cases = []
    current_ids = []
    current_body = []
    i = start_idx

    while i < len(lines):
        line = lines[i]
        if is_switch_end(line):
            if current_ids:
                cases.append((current_ids, current_body))
            break

        case_match = CASE_PATTERN.match(line)
        if case_match:
            if current_ids:
                cases.append((current_ids, current_body))
                current_ids = []
                current_body = []
            current_ids.append(case_match.group(2))
            inline_code = case_match.group(3).strip()
            if inline_code and not inline_code.startswith('//'):
                current_body.append(inline_code)
        elif not BREAK_PATTERN.match(line.strip()):
            stripped = line.rstrip()
            if stripped.strip() or '//' in stripped or '/*' in stripped:
                current_body.append(stripped)
            else:
                current_body.append('')
        i += 1
    else:
        if current_ids:
            cases.append((current_ids, current_body))

    if not cases:
        return None, start_idx

    new_lines = []
    for idx, (ids, body) in enumerate(cases):
        cond = " || ".join(f"{var_name}.getId() == {id_}" for id_ in ids)
        if idx == 0:
            new_lines.append(f"{base_indent}if ({cond}) {{")
        else:
            new_lines.append(f"{base_indent}}} else if ({cond) {{")
        for b in body:
            if b == '':
                new_lines.append('')
            elif b.strip().startswith(('//', '/*')):
                new_lines.append(b)
            else:
                # 保持原始缩进或加一层
                inner_indent = base_indent + "    "
                new_lines.append(inner_indent + b.lstrip())
    new_lines.append(f"{base_indent}}}")
    return new_lines, i + 1

def process_file(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8-sig') as f:
            lines = f.readlines()
    except Exception:
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                lines = f.readlines()
        except Exception:
            with open(file_path, 'r', encoding='gbk') as f:
                lines = f.readlines()

    new_lines = []
    i = 0
    modified = False

    while i < len(lines):
        line = lines[i]
        param = get_onclick_param(line)
        if param is not None:
            var_name = param
            switch_found = False
            # 在接下来最多 15 行内查找 switch
            for j in range(i + 1, min(i + 16, len(lines))):
                sw_var = get_switch_var(lines[j])
                if sw_var == var_name:
                    # 获取 switch 行的缩进
                    switch_line = lines[j]
                    base_indent = switch_line[:len(switch_line) - len(switch_line.lstrip())]
                    converted, next_i = process_switch_block(lines, j + 1, var_name, base_indent)
                    if converted is not None:
                        # 保留 onClick 行，替换 switch 块
                        new_lines.append(line)
                        new_lines.extend(converted)
                        i = next_i
                        modified = True
                        switch_found = True
                        break
            if not switch_found:
                new_lines.append(line)
                i += 1
        else:
            new_lines.append(line)
            i += 1

    if modified:
        with open(file_path, 'w', encoding='utf-8', newline='\n') as f:
            f.writelines(new_lines)
        print(f"✅ 转换成功: {file_path}")
        return True
    else:
        print(f"❌ 未找到可转换的 onClick + switch 结构: {file_path}")
        return False

def main():
    if len(sys.argv) != 2:
        print("用法: python convert_switch_to_if.py <Java文件或目录>")
        sys.exit(1)

    path = Path(sys.argv[1])
    if path.is_file():
        if path.suffix != '.java':
            print("❌ 请提供 .java 文件")
            sys.exit(1)
        java_files = [path]
    else:
        java_files = [
            f for f in path.rglob("*.java")
            if not any(p in str(f) for p in ['build', '.gradle', 'generated', 'R.java', 'BuildConfig.java'])
        ]

    print(f"🔍 扫描 {len(java_files)} 个 Java 文件...")
    count = sum(process_file(str(f)) for f in java_files)
    print(f"\n🎉 完成！共转换 {count} 个文件。")

if __name__ == '__main__':
    main()